package edu.shiep.sunyu;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

import edu.shiep.sunyu.model.Bus;
import edu.shiep.sunyu.model.DBClient;
import edu.shiep.sunyu.model.DBConstants;
import edu.shiep.sunyu.model.Database;
import edu.shiep.sunyu.model.Table;

public class AdminAddBusLineServlet extends HttpServlet {

	private static final long serialVersionUID = 8691758354120690378L;
	
	private DBClient _client = null;
	
	public void init(ServletConfig config) throws ServletException {
	   super.init(config);
	   
	   _client = new DBClient();
	   if (!_client.connect()) {
		   System.out.println("Can't connect to database!!!");
	   }
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// reading the user input
		String busid = request.getParameter("bus_id");
		String bus_line = request.getParameter("bus_line");
		String bus_seat = request.getParameter("bus_seat");
		String bus_reserve = request.getParameter("bus_reserve");
		String bus_ahead = request.getParameter("bus_ahead");
		
		if (!Utility.isInteger(bus_seat) || !Utility.isInteger(bus_reserve) || !Utility.isInteger(bus_ahead)) {
			// forward back to add bus line page
			// set page error message
			request.setAttribute("msg",	"The format of reserving time or ahead time is invalid. Please try again.");
			
			RequestDispatcher view = request.getRequestDispatcher("AdminAddBusLine.jsp");
			view.forward(request, response);
			return;
		}
		
		Database db = _client.getDB(DBConstants.Const_Database_Name);
		
		Table table = db.getTable(DBConstants.Const_Table_Bus_Name);
		
		BasicDBObject query = new BasicDBObject();
		query.put("bus_id", busid);
		
		DBCursor cursor = table.query(query);
		if (cursor.size() != 0) {
			// forward back to add bus line page
			// set page error message
			request.setAttribute("msg",	"The bus line has existed. Please try again.");
			
			RequestDispatcher view = request.getRequestDispatcher("AdminAddBusLine.jsp");
			view.forward(request, response);
			return;
		}
		
		BasicDBObject document = new BasicDBObject();
		document.put(Bus.Field_Id, busid);
		document.put(Bus.Field_Line, bus_line);
		document.put(Bus.Field_Seat, bus_seat);
		document.put(Bus.Field_Reserve, bus_reserve);
		document.put(Bus.Field_Ahead, bus_ahead);
		
		table.insert(document);
		
		// forward to admin page
		request.setAttribute("msg",	"The bus line has been added successfully. Please add another one.");
		
		RequestDispatcher view = request.getRequestDispatcher("AdminAddBusLine.jsp");
		view.forward(request, response);
	}  
}
